/**
 * 获取商品详情信息
 * @param {*} goodsId 
 * @returns 
 */
exports.getGoodsDetail = (goodsId) => {
  const { getFile } = require('../models/getfile')
  const model = require('../models/model')
  const MyGoods = model.goodsdetails.MyGoods
  const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku //获取模型
  const MyGoodsListType = model.goodsdetailsType.MyGoodsListType //获取模型
  const MyGoodsList = model.goodsdetailsList.MyGoodsList //获取模型
  // 获取sku异步
  function skuListFn(skus, id) {
    return new Promise(async (resolve, reject) => {
      let data = []
      if (skus.length > 0) {
        let flag = 0
        for (let i = 0; i < skus.length; i++) {
          await getSkuItem(skus[i]).then(value => {
            flag++
            data.push(value)
            if (flag === skus.length) {
              resolve(data)
            }
          })
        }
      } else {
        resolve(data)
      }
      // 具体方法
      function getSkuItem(skuKey) {
        return new Promise(async (resolve) => {
          const sku = await MyGoodsListSku.findOne({
            where: {
              k_S: skuKey
            }
          }) // 获取父类
          const skuItem = await MyGoodsListType.findAll({
            where: {
              skuId: sku.id,
              parentId: id
            }
          }) // 获取子类
          sku['v'] = skuItem
          // 获取图片
          let flag = 0
          sku['v'].forEach(item => {
            getFile(item.previewImgUrl).then(data => {
              flag++
              item['previewImgUrl'] = data
              item['imgUrl'] = data
              if (flag === sku.v.length) { // 循环完成
                resolve(sku)
              }
            })
          })
        })
      }
    })
  }

  function listFn(id) {
    return new Promise(async (resolve) => {
      const res = await MyGoodsList.findAll({
        where: {
          parentId: id
        }
      })
      if (res.length > 0) {
        res.forEach(item => {
          for (let prop in item) {
            if (!item[prop]) {
              delete item[prop]
            }
          }
        })
        resolve(res)
      } else {
        resolve(res)
      }
    })
  }
  return new Promise(async (resolve) => {
    const res = await MyGoods.findOne({
      where: {
        id: goodsId
      }
    })
    if (res) { // 获取商品详情后 继续获取sku和list列表
      res['none_sku'] = res.none_sku != 0
      res['sku'] = res.sku.split(',').filter(item => item !== '')
      res['skuList'] = await skuListFn(res.sku, res.id)
      res['list'] = await listFn(res.id)
      res['iconId'] = await getFile(res.iconId)
      res['homeImageIds'] = await getFile(res.homeImageIds)
      res['detailsImageIds'] = await getFile(res.detailsImageIds)
      resolve(res)
    } else {
      resolve({})
    }
  })
}